Creating reusable themes

Elizabeth King
Kevin Middleton

Why reusable themes?

  • Many plots share a scale_color, scale_fill, scale_linetype, or scale_shape
  • Many plots get the same axis text or title treatment
    • Font family, face, size, color
    • Useful for making plots for presentations (powerpoint/equivalent or poster)
  • Save time for your future self

Trunks data

  • DBH and trunk flare for 4 species of maple
# A tibble: 275 × 4
   Species          City        DBH    TF
   <chr>            <chr>     <int> <dbl>
 1 Acer platanoides Rochester    23   8.7
 2 Acer platanoides Rochester    21   6.5
 3 Acer platanoides Rochester    21   6.8
 4 Acer platanoides Rochester    16   6.7
 5 Acer platanoides Rochester    16   9  
 6 Acer platanoides Rochester    28  12.7
 7 Acer platanoides Rochester    16   7.5
 8 Acer platanoides Rochester    14   6.8
 9 Acer platanoides Rochester    21   7.9
10 Acer platanoides Rochester    16   5.2
# ℹ 265 more rows

Violin & Sina plot

ggplot(Trunks, aes(x = Species, y = DBH, color = Species)) +
  geom_violin() +
  geom_sina(seed = 74645) +
  scale_color_manual(values = c("red", "orange", "blue", "purple"),
                     breaks = c("Acer saccharinum", "Acer rubrum",
                                "Acer platanoides", "Acer saccarum")) +
  theme(axis.title = element_text(face = "bold"),
        axis.text.x = element_text(face = "italic")) +
  guides(color = "none")

Violin & Sina plot

Creating your own reusable theme

  • In ggplot, elements are added with +
  • Convert to a list, separate items with ,
mytheme <- list(
  scale_color_manual(values = c("red", "orange", "blue", "purple"),
                     breaks = c("Acer saccharinum", "Acer rubrum",
                                "Acer platanoides", "Acer saccarum")),
  theme(axis.title = element_text(face = "bold"))
)

ggplot(Trunks, aes(x = Species, y = DBH, color = Species)) +
  geom_violin() +
  geom_sina(seed = 74645) +
  mytheme +
  guides(color = "none") +
  theme(axis.text.x = element_text(face = "italic"))

Creating your own reusable theme

Reuse your theme in a Sina plot

ggplot(Trunks, aes(x = Species, y = TF, color = Species)) +
  geom_violin() +
  geom_sina(seed = 74645) +
  mytheme +
  guides(color = "none") +
  theme(axis.text.x = element_text(face = "italic"))

Reuse your theme in a Sina plot

Reuse your theme in a scatter plot

ggplot(Trunks, aes(x = DBH, y = TF, color = Species)) +
  geom_point() +
  mytheme +
  guides(color = guide_legend(label.theme = element_text(face = "italic"))) +
  theme(legend.position = "inside",
        legend.position.inside = c(0.7, 0.2))

Reuse your theme in a scatter plot

Managing multiple themes

  • Data exploration theme
  • Paper theme
  • Poster theme

All in the same document